﻿#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <iostream>
#include <string>
#pragma comment(lib, "ws2_32.lib")

#define SERVER_IP "127.0.0.1"
#define PORT 8888

std::string send_cmd(const std::string& cmd) {
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
    SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    inet_pton(AF_INET, SERVER_IP, &addr.sin_addr);
    connect(s, (sockaddr*)&addr, sizeof(addr));
    send(s, cmd.c_str(), cmd.size(), 0);
    char buf[256] = { 0 };
    int len = recv(s, buf, sizeof(buf) - 1, 0);
    closesocket(s);
    WSACleanup();
    return std::string(buf, len);
}

int main() {
    std::string serial, username;
    std::cout << "请输入序列号（首次注册输入0）: ";
    std::cin >> serial;
    if (serial == "0") {
        std::string password, type;
        std::cout << "用户名: "; std::cin >> username;
        std::cout << "口令: "; std::cin >> password;
        std::cout << "许可证类型(10/50): "; std::cin >> type;
        std::string cmd = "REGISTER " + username + " " + password + " " + type;
        serial = send_cmd(cmd);
        std::cout << "获得序列号: " << serial << std::endl;
    }
    else {
        std::cout << "用户名: "; std::cin >> username;
        std::string cmd = "AUTH " + serial + " " + username;
        std::string resp = send_cmd(cmd);
        if (resp == "ALLOW") {
            std::cout << "授权成功，开始使用软件..." << std::endl;
            // 模拟心跳
            while (true) {
                Sleep(10000); // 10秒
                std::string hb = "HEARTBEAT " + serial + " " + username;
                send_cmd(hb);
                std::cout << "已发送心跳" << std::endl;
            }
        }
        else {
            std::cout << "授权失败，用户数已满或序列号无效。" << std::endl;
        }
    }
    return 0;
}